package com.datastructures2.graph.无向图;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.ST;

/**
 * 符号图的数据类型
 * @author MaoLin Wang
 * @date 2020/2/2119:50
 */
public class SymbolGraph {
    /**
     * key : 符号名
     * value： 索引
     */
    private ST<String,Integer>st;
    /**
     * 索引 -> 符号名
     * keys[1]=aaa 索引为1的符号名是aaa
     */
    private String[] keys;

    private Graph graph;

    public SymbolGraph(String stream,String sp){
        st=new ST<>();
        In in=new In(stream);
        while (in.hasNextLine()){
            String[] a=in.readLine().split(sp);
            for (int i = 0; i < a.length; i++) {
                if (!st.contains(a[i])){
                    st.put(a[i],st.size());
                }
            }
        }
        keys=new String[st.size()];
        for (String name:st.keys()){
            keys[st.get(name)]=name;
        }
        graph=new Graph(st.size());
        //第二遍 构造图
        in=new In(stream);
        while (in.hasNextLine()){
            //将每一行的第一个顶点和该行的其他顶点相连
            String[]a=in.readLine().split(sp);
            int v = st.get(a[0]);
            for (int i = 1; i < a.length; i++) {
                graph.addEdge(v,st.get(a[i]));
            }
        }
    }

    public boolean contains(String s){
        return st.contains(s);
    }
    public int index(String s){
        return st.get(s);
    }
    public String name(int v){
        return keys[v];
    }
    public Graph G(){
        return graph;
    }

    public static void main(String[] args) {
        SymbolGraph symbolGraph=new SymbolGraph("D:\\JavaProject\\算法\\数据结构和算法\\DATAStructures\\alg\\src\\main\\java\\com\\datastructures2\\graph\\routes.txt",",");;
        Graph graph = symbolGraph.G();
        System.out.println(symbolGraph.name(2));
        System.out.println(graph);

    }
}
